package com.example.fengyungo.service.impl;

import com.example.fengyungo.constant.MsgConstant;
import com.example.fengyungo.dao.AdminDao;
import com.example.fengyungo.dao.DriverDao;
import com.example.fengyungo.dao.UserDao;
import com.example.fengyungo.domain.pojo.Admin;
import com.example.fengyungo.domain.pojo.Driver;
import com.example.fengyungo.domain.pojo.LoginUser;
import com.example.fengyungo.domain.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 实现UserDetailsService接口，重写其中的方法。增加用户名从数据库中查询用户信息
 * @author 徐
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private DriverDao driverDao;

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息

        // 管理员
        Admin admin = adminDao.getAdminByUsernameAndPassword(username);
        // 如果用户是管理员
        if (admin != null) {
            log.info("admin：" + admin);
            return new LoginUser(admin);
        }

        // 司机
        Driver driver = driverDao.getDriverByUsername(username);
        if (driver != null) {
            log.info("driver：" + driver);
            return new LoginUser(driver);
        }

        // 用户
        List<User> users = userDao.getUserByUsername(username);
        // 如果查询不到数据就通过抛出异常来给出提示
        if (users.size() == 0) {
            throw new UsernameNotFoundException(MsgConstant.USERNAME_OR_PASSWORD_ERROR);
        } else {
            log.info("user：" + users.get(0));
            return new LoginUser(users.get(0));
        }
    }
}
